package club.zhangliyuanblog.controller;

import club.zhangliyuanblog.entity.CommonResult;
import club.zhangliyuanblog.entity.Payment;
import club.zhangliyuanblog.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liyuan.zhang
 * @date 2021/4/17 17:15
 */
@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public CommonResult<Integer> create(@RequestBody Payment payment) {
        int i = paymentService.create(payment);
        log.info("影响行数{}", i);
        if (i > 0) {
            return new CommonResult<>(200, "插入成功,机器端口号为：" + serverPort, i);
        }
        return new CommonResult<>(400, "插入失败", null);
    }

    @GetMapping("/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable Long id) {
        log.info("测试热部署");
        Payment payment = paymentService.getPaymentById(id);
        return new CommonResult<>(200, "查询成功，机器端口：" + serverPort, payment);
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*******element:{}", service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/lb")
    public String testLB() {
        return serverPort;
    }


    /**
     * 测试Feign超时
     * @param timeout
     * @return
     * @throws InterruptedException
     */
    @GetMapping(value = "/timeout/{timeout}")
    public String testFeignTimeOut(@PathVariable("timeout") Integer timeout) throws InterruptedException {
        Thread.sleep(timeout * 1000);
        return "success";
    }
}
